package org.llama.jmex.terra;

import com.jme.bounding.BoundingBox;
import com.jme.renderer.Renderer;
import com.jme.scene.VBOInfo;
import com.jme.system.DisplaySystem;

public class SimpleTerraMesh extends TerraMesh{
	public final boolean deleteVBO;
	public final boolean ditchVBO;
	
	public SimpleTerraMesh(SimpleTerraData terra) {
		super(terra.terraManager.getName()+":"+terra.upperx+":"+terra.uppery);
		this.xy = terra.xy;
		deleteVBO = terra.terraProperties.useDeleteVBO;
		ditchVBO = terra.terraProperties.useDitchVBO;
		buildTerra(terra);		
	}
	
	
	public void buildTerra(TerraData terraData) {
		SimpleTerraData terra = (SimpleTerraData) terraData;
		reconstruct(terra.verticesbuffer, terra.normalbuffer, null, terra.texturebuffer, terra.indicesbuffer);
		setDefaultColor(terra.terraProperties.defaultColor);
		setLocalTranslation(terra.origin);

		setModelBound(new BoundingBox());
        updateModelBound();
        
        this.setLocalTranslation(terra.origin);
        
        
        if (terra.terraProperties.useVBO) {
        	this.setVBOInfo(new VBOInfo(true));
        	if (terra.terraProperties.useIndicisVBO)
        		this.getVBOInfo(0).setVBOIndexEnabled(true);        	
        }
        else {
        	this.setVBOInfo(new VBOInfo(false));
        }
//        this.getVBOInfo().setVBONormalEnabled(false);
        
//        if (vboinfo == null) {
//	        this.setVBOInfo(vboinfo = new VBOInfo(true));
////	        vboinfo.setVBOIndexEnabled(false);
//        }
        if (terra.terraProperties.useLocking) {
	       this.lockBounds();
	       this.lockTransforms();
        }
        
	}
	
	
	
	
	public void deleteVBOs() {
		if (!deleteVBO)
			return;
		System.out.println("del. VBOS: "+id);
		deleted = true;
		DisplaySystem.getDisplaySystem().getRenderer().deleteVBO(this.getVertexBuffer(0));
		DisplaySystem.getDisplaySystem().getRenderer().deleteVBO(this.getNormalBuffer(0));
		getVBOInfo(0).setVBOVertexID(-1);
		getVBOInfo(0).setVBONormalID(-1);
	}
	
	public void draw(Renderer r) {
		if (deleted) {
		}
		super.draw(r);
		
		if (ditch && getVertexBuffer(0) != null) {
			this.setVertexBuffer(0,null);
			System.out.println("ditched vertex buffer("+id+"):"+this.getVBOInfo(0).getVBOVertexID());
			this.setNormalBuffer(0,null);
			System.out.println("ditched normal buffer("+id+"):"+this.getVBOInfo(0).getVBONormalID());

		}
		
		if (ditchVBO) {
			if (!ditch && this.getVertexBuffer(0) != null && this.getVBOInfo(0).getVBOVertexID() > 0 
					&& this.getNormalBuffer(0) != null && this.getVBOInfo(0).getVBONormalID() > 0 ) 
				ditch = true;
			
		}

	}
	
	public void cleanUp() {
		deleteVBOs();
	}
	
}
